<template>
  <div class="add-close-adv-container">
    <!-- 表单头部 -->
    <div class="form-header">
      <h2 class="title">闭环医嘱信息</h2>
    </div>

    <!-- 主内容区域 -->
    <el-form 
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="220px"
      class="form-content"
      :loading="loading"
    >
      <!-- 医嘱中文名称 -->
      <el-form-item 
        label="医嘱中文名称 :"
        prop="NODE_NAME"
      >
        <el-input
          :value="props.nodeName"
          disabled
          :maxlength="30"
          clearable
        />
      </el-form-item>

      <!-- 医嘱英文名称 -->
      <el-form-item 
        label="医嘱英文名称（视图名称） :"
        prop="BASE_TABLE_NAME"
      >
        <el-input
          v-model="formData.BASE_TABLE_NAME"
          placeholder="请输入1-30个英文字符"
          :maxlength="30"
          clearable
          @blur="inputCheck(1)"
          @input="inputCheck(1)"
        />
      </el-form-item>

      <!-- 多次执行记录 -->
      <el-form-item 
        label="一条医嘱是否可能包含多次执行记录 :"
        class="switch-item"
        prop="HAVE_MANY_TIMES"
      >
        <el-switch
          v-model="formData.HAVE_MANY_TIMES"
          :active-value="1"
          :inactive-value="0"
          active-color="#007077"
          inactive-color="#999999"
        />
      </el-form-item>

      <!-- 数据源 -->
      <el-form-item 
        label="数据源 :"
        prop="dataSourceId"
      >
        <el-select
          v-model="formData.dataSourceId"
          placeholder="指定数据源（可以为空）"
          class="select-input"
        >
          <el-option
            v-for="item in dataSourceList"
            :key="item.BASE_ID"
            :label="item.BASE_NAME"
            :value="item.BASE_ID"
          >
            <span :style="{ color: item.BASE_ID === -1 ? '#ff9900' : '#8492a6' }">
              {{ item.BASE_NAME }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>

  <div class="field-config-container">
    <!-- 字段配置 -->
    <div class="section-header">
      <h3>字段配置 <span class="subtitle">（*代表固定字段）</span></h3>
    </div>
    <div class="field-config-list">
      <div 
        v-for="(field, index) in configFields" 
        :key="index" 
        class="field-item"
      >
        <div class="field-label">
          <span v-if="field.isRequired" class="required">*</span>
          {{ field.displayName }}（{{ field.fieldName }}）
        </div>
        <div class="equal-sign">等于</div>
        <el-input
        :value="field.value" 
        :disabled="field.fieldName === 'close_index'" 
        :placeholder="field.placeholder"
        @input="(val) => field.value = val"
        class="input-field"
        clearable
        />
      </div>
    </div>

    <!-- 按钮组 -->
    <div class="button-group">
      <el-button type="primary" @click="handleNextStep">保 存</el-button>
      <el-button 
        v-if="showErrorDialog" 
        type="danger" 
        @click="showErrorDetails"
      >
        查看错误信息
      </el-button>
    </div>

    <!-- 错误提示对话框 -->
    <el-dialog 
      title="错误提示" 
      v-model="dialogVisible"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="错误信息" name="digerr">
          <pre class="error-details">{{ errorInfo }}</pre>
        </el-tab-pane>
        <el-tab-pane label="SQL信息" name="digsql">
          <pre class="error-details">{{ sqlInfo }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed ,defineProps,watch} from 'vue'
import { ElMessage } from 'element-plus'
import { 
  closeLoopDetailNodes as useCloseLoopNodesStore,
  closeLoopDetailYzBase as useCloseLoopYzBaseStore,
  closeLoopDetailCloumn as useCloseLoopColumnStore
} from '@/stores/closeLoopList' 

// 实例化三个Store
const closeLoopNodesStore = useCloseLoopNodesStore()
const closeLoopYzBaseStore = useCloseLoopYzBaseStore()
const closeLoopColumnStore = useCloseLoopColumnStore()

// Props 接收 NODE_ID
const props = defineProps({
  nodeId: {
    type: String,
    required: true
  },
  nodeName: {  // 新增：接收 node_name
    type: String,
    default: ''
  },
  nodeNum: { // 新增：接收节点顺序
    type: Number,
    default: 0
  }
})

const loading = ref(false)
const dialogVisible = ref(false)
const activeTab = ref('digerr')
const errorInfo = ref('')
const sqlInfo = ref('')
const showErrorDialog = ref(false)

// 表单数据
const formData = reactive({
  BASE_TABLE_NAME: '',
  HAVE_MANY_TIMES: 0,
  dataSourceId: '-1',
})

// 字段配置
const configFields = reactive([
  {
    displayName: '节点名称',
    fieldName: 'close_name',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '节点名称 不能为空'
  },
  {
    displayName: '节点顺序',
    fieldName: 'close_index',
    isRequired: true,
    value: props.nodeNum.toString(), // 显式绑定 Props
    error: false,
    errorMessage: '节点顺序 不能为空'
  },
  {
    displayName: '执行时间',
    fieldName: 'close_time',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '执行时间 不能为空'
  },
  {
    displayName: '执行人',
    fieldName: 'close_doc',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '执行人 不能为空'
  },
  {
    displayName: '科室',
    fieldName: 'close_dept',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '科室 不能为空'
  },
  {
    displayName: '执行状态',
    fieldName: 'close_type',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '执行状态 不能为空'
  },
  {
    displayName: '医嘱号',
    fieldName: 'order_no',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '医嘱号 不能为空'
  },
  {
    displayName: '执行组号',
    fieldName: 'order_group',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '执行组号 不能为空'
  },
  {
    displayName: '额外展示字段',
    fieldName: 'extra_field',
    isRequired: false,
    value: '',
    error: false,
    errorMessage: ''
  }
])

// 数据源列表（从YzBase Store获取）
const dataSourceList = computed(() => closeLoopYzBaseStore.dataSourceList)

// 加载数据
const fetchData = async () => {
  if (!props.nodeId) {
    ElMessage.error('缺少节点ID，请检查参数传递')
    return
  }
  loading.value = true
  try {
    // 使用 props.nodeId 替代路由参数
    const nodeId = props.nodeId

    // 1. 获取闭环详情（主数据）
    await closeLoopNodesStore.getCloseLoopDetailNodes(nodeId)

    // 2. 更新表单数据
    const nodeData = closeLoopNodesStore.closeLoopDetailNodesList[0] || {}
    Object.assign(formData, {
      NODE_NAME: nodeData.NODE_NAME || '',
      BASE_TABLE_NAME: nodeData.BASE_TABLE_NAME || '',
      HAVE_MANY_TIMES: Number(nodeData.HAVE_MANY_TIMES) || 0,
      dataSourceId: nodeData.BASE_ID || '-1'
    })

    // 3. 获取数据源列表
    await closeLoopYzBaseStore.fetchCloseLoopBaseList()

    // 4. 获取字段配置
    await closeLoopColumnStore.getCloseLoopDetailList(nodeId)

    // 5. 初始化 configFields 的 value
    const columnList = closeLoopColumnStore.closeLoopDetailColumnList || []
    const columnMap = {}
    columnList.forEach(item => {
      const lowerName = item.COLUMN_NAME.toLowerCase()
      columnMap[lowerName] = item.COLUMN_SQL || ''
    })

    // 更新字段值并排序
    configFields.forEach(field => {
      field.value = columnMap[field.fieldName] || ''
    })

    // 根据ORDER_NUM排序
    configFields.sort((a, b) => {
      const aOrder = columnList.find(
        item => item.COLUMN_NAME === a.fieldName.toUpperCase()
      )?.ORDER_NUM || 0
      const bOrder = columnList.find(
        item => item.COLUMN_NAME === b.fieldName.toUpperCase()
      )?.ORDER_NUM || 0
      return aOrder - bOrder
    })
  } catch (error) {
    console.error('获取闭环详情失败:', error)
    ElMessage.error(`获取数据失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  fetchData()
})

// 表单验证
const rules = {
  NODE_NAME: [
    { required: true, message: '请输入医嘱中文名称', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在1到30个字符', trigger: 'blur' }
  ],
  BASE_TABLE_NAME: [
    { required: true, message: '请输入医嘱英文名称', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在1到30个字符', trigger: 'blur' }
  ]
}

// 保存操作
// const handleNextStep = async () => {
//   // 验证表单
//   const allValid = configFields.every(field => !field.error)
//   if (!allValid) {
//     showErrorDialog.value = true
//     ElMessage.error('存在未通过验证的字段')
//     return
//   }

//   // 这里添加保存逻辑（根据你的业务需求）
//   // 例如：调用API提交数据
//   // 示例：
//   try {
//     // 保存到Store或API
//     await someSaveFunction()
//     ElMessage.success('保存成功')
//   } catch (error) {
//     ElMessage.error('保存失败')
//   }
// }

// 错误详情
const showErrorDetails = () => {
  dialogVisible.value = true
}
watch(
  () => props.nodeNum,
  (newVal) => {
    const targetField = configFields.find(f => f.fieldName === 'close_index');
    if (targetField) {
      targetField.value = newVal.toString();
    }
  }
);

// 确保挂载后数据正确
onMounted(() => {
  console.log('组件已挂载，节点顺序值:', configFields[0].value);
});
</script>

<style scoped>
/* 添加样式（根据你的实际样式调整） */
.add-close-adv-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.form-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  color: #333;
}

.form-content {
  max-width: 800px;
}

.field-config-container {
  margin-top: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.section-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
  margin-bottom: 15px;
}

.subtitle {
  color: #999;
  font-size: 14px;
}

.field-config-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.field-label {
  width: 180px;
  font-weight: bold;
}

.required {
  color: red;
  margin-right: 4px;
}

.equal-sign {
  margin: 0 10px;
}

.input-field {
  flex: 1;
}

.button-group {
  margin-top: 20px;
  text-align: right;
}

.error-details {
  white-space: pre-wrap;
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>